package org.ccay.core.util;

import java.util.Arrays;
import java.util.regex.Pattern;

import org.ccay.core.ioc.Ccay;
import org.ccay.core.registry.IRegistryManager;
import org.ccay.core.request.impl.RequestContext;
import org.springframework.util.StringUtils;

public final class LanguageUtil {
	
	private LanguageUtil(){
	}
	public static final Pattern pattern = Pattern.compile("[a-z]{2}_[A-Z]{2}="); 
	
	/**
	 * 注册项管理器
	 */
	private static IRegistryManager registryManager;
	
	/**
	 * 依据传入的analyticString属性列返回当前语种的显示值
	 * 
	 * @param analyticString
	 * @param language
	 * @param allLanguages
	 * @return
	 */
	public static String getLanguageStr(String analyticString, String language,String[] allLanguages) {
		// 如果没有任何语种，直接返回待解析的列名或sheet名
		if (StringUtil.isNullOrEmpty(analyticString)
				|| !pattern.matcher(analyticString).find()) {
			return analyticString;
		}
		// 在所有有效语种格式为",[a-z]{2}_[A-Z]{2}="形式
		String[] validLans = StringUtils.collectionToDelimitedString(
				Arrays.asList(allLanguages), "@@", ",", "=").split("@@");
		// 在列属性名前加','用于判断截取
		String tempAnalyticStr = "," + analyticString;
		// 在语种前加','，后加'='用于判断截取
		String localeStr = "," + language + "=";
		// 获取当前language在待解析的列名或sheet名中的位置
		int localIndex = tempAnalyticStr.indexOf(localeStr);
		
		int nextIndex = -1;
		int tempIndex = -1;
		int smallestDiff = Integer.MAX_VALUE;
		boolean valuedata = false;
		
		//根据当前有效语种查询到下一个有效语种
		for (String tempLan : validLans) {
			tempIndex = tempAnalyticStr.indexOf(tempLan);
			if (tempIndex > 0) {
				valuedata = true;
			}
			if (tempIndex > localIndex && (tempIndex - localIndex) < smallestDiff) {
				smallestDiff = tempIndex - localIndex;
				nextIndex = tempIndex;
			}
		}

		// 当前语种不存在 但是其他语种存在 返回"" 否则返回待解析的列名或sheet名
		if (localIndex == -1) {
			return valuedata ? "" : analyticString;
		}

		return nextIndex == -1 ? tempAnalyticStr.substring(localIndex
				+ localeStr.length()) : tempAnalyticStr.substring(localIndex
				+ localeStr.length(), nextIndex);
		
	}
	
	/**
	 * 依据传入的analyticStr属性列返回指定语种的显示值
	 * @param analyticStr
	 * @param language
	 * @return
	 */
	public static String getLanguageStr(String analyticStr,String language){
		
		return getLanguageStr(analyticStr,language,getValidLanguages());
	}
    /**
     * 依据传入的analyticStr属性列返回当前语种的显示值
     * @param analyticStr
     * @return
     */
    public static String getCurrenLanguageStr(String analyticStr){
		return getLanguageStr(analyticStr,RequestContext.getCurrent().getUserLanguage(),getValidLanguages());
	}
	/**
	 * 获取所有有效语种
	 * @return
	 */
	public static String[]  getValidLanguages(){
		if(null == registryManager){
			registryManager = Ccay.getContext().getBean("registryManager", IRegistryManager.class);
		}
		return registryManager.getValue("Ccay.GlobalParamters.ValidLanguages").split(",");
	}
	
}
